<template>
  <div class="state-ment-main guanwang-bg" style="height: calc(100vh - 124px);border-radius: 10px">
    <div :style="{paddingTop:100 * (10 / screensStore.bodyHeight) + 'vh',
    paddingLeft:100 * (10 / screensStore.bodyWidth) + 'vw',paddingRight:100 * (10 / screensStore.bodyWidth) + 'vw',
    marginBottom:100 * (10 / screensStore.bodyHeight) + 'vh'}"
         v-if="isEmpty">
      <div class="title-desp">{{screensStore.selPeriodObj.periodName}}</div>
      <div style="margin-top: 20px">
        <el-form :inline="true" :model="searchData" class="demo-form-inline" style="width: 100%">
          <el-form-item>
            <el-tag
              type="primary"
              effect="dark"
              round
            >
              单店报表查看
            </el-tag>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchData.state" placeholder="请选择状态" style="width: 200px">
              <el-option label="全部" value="全部" />
              <el-option label="访问员录入" value="访问员录入" />
              <el-option label="QC审核" value="QC审核" />
              <el-option label="厂商审核" value="厂商审核" />
              <el-option label="终审结束" value="终审结束" />
            </el-select>
          </el-form-item>
          <el-form-item label="网点简称">
            <el-input v-model="searchData.outletsName" placeholder="请输入网点简称" />
          </el-form-item>
          <el-form-item label="省市区">
            <el-cascader
              :options="screensStore.proviceList"
              v-model="searchData.addressList"
              :props="{value:'label'}"
              clearable></el-cascader>
          </el-form-item>
          <el-form-item label="切换层级">
            <el-cascader
              :options="daQuyuList"
              placeholder="请选择层级" clearable
              v-model="levelId1"
              :props="{ multiple: true, checkStrictly: true,value:'tree',label:'outletsName',emitPath:false}"
            ></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearchList"><el-icon><Search /></el-icon>查询</el-button>
            <el-button @click="onClearList"><el-icon><Refresh /></el-icon>重置</el-button>
            <el-button type="primary" @click="onExportData"><el-icon><Promotion /></el-icon>导出全部报表信息</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 100%;display: flex;justify-content: flex-end">
        <down-table-show-sort :tablePropsArr="tablePropsArr" @throwTableProps="getTablePropsList"></down-table-show-sort>
      </div>
      <div>
        <el-table :data="tableData" border style="width: 100%" :tooltip-formatter="tableRowFormatter"
                  :header-cell-style="{ background: 'rgb(250,250,250)'}">
          <el-table-column label="序号" type="index" :index="indexMethod" width="80px" align="center"/>
          <template v-for="item in tablePropsArr">
            <el-table-column  :prop="item.prop" :label="item.label" align="center"
                              :key="item.prop" :width="item?.width ?  item?.width : 'auto'" v-if="item.isHidden">
              <template #default="scope">
                <div v-if="item.prop == 'state'">
                  <el-tag
                    v-if="scope.row.state == '访问员录入'"
                    type="primary"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.state == 'QC审核'"
                    type="success"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.state == '厂商审核'"
                    type="warning"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.state == '终审结束'"
                    type="danger"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                  <el-tag
                    v-else
                    type="danger"
                    effect="dark"
                  >
                    {{ scope.row.state }}
                  </el-tag>
                </div>
                <div v-else>
                  <el-tooltip
                    class="box-item"
                    effect="light"
                    :content="scope.row[item.prop]"
                    placement="top"
                  >
                    <div class="text-overflow">
                      {{scope.row[item.prop]}}
                    </div>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </template>
          <el-table-column prop="handle" label="操作" align="center" width="180px"
          fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="openInputDrawer(0,scope.row)"
              >
                查看
              </el-button>
              <el-button
                type="danger"
                link
                v-if="scope.row.type == 1 && scope.row.isEnd == 1 && screensStore.roles && (screensStore.roles.findIndex(item =>
                item == 'admin') != -1)"
                @click="startFanshen(scope.row)"
              >
                反审
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="fixed-row" style="width: 100%;justify-content: center;margin-top: 10px">
          <el-pagination background layout="sizes,prev,pager,next,jumper,total" :total="paging.total"
                         @size-change="changeSize" @current-change="changeCurrent"/>
        </div>
      </div>
    </div>
    <div v-else style="width: 100%;height: 100%">
      <el-empty description="请先选择期次">
        <el-button type="primary" @click="toIssueselect">选择期次</el-button>
      </el-empty>
    </div>

    <el-drawer
      v-model="inputDrawer"
      title="报表查看"
      size="100%"
      class="el-drawer__body"
      :append-to-body="true"
    >
      <el-card style="margin-bottom: 20px">
        <div class="fixed-row">
          <div style="margin-right: 10px;font-size:14px">基本信息</div>
          <div><el-button type="primary" link @click="downloadPDF">导出PDF</el-button></div>
<!--          <div><el-button type="primary" link @click="downloadDOCX">导出DOCX</el-button></div>-->
        </div>
        <div style="margin: 10px 0">
          <el-descriptions
            class="margin-top"
            :column="4"
            border
          >
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  网点：
                </div>
              </template>
              {{baoBiaoInfo?.outletsName || '无'}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  所属地区：
                </div>
              </template>
              {{baoBiaoInfo?.provinceName || '无'}} {{baoBiaoInfo?.cityName}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  所属层级：
                </div>
              </template>
              {{baoBiaoInfo?.outletsLevelName || '无'}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  报告时间：
                </div>
              </template>
              {{baoBiaoInfo?.reportTime || '无'}}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="fixed-row" style="justify-content: space-between;padding: 0 80px" v-if="inputDrawer">
          <div style="display: flex;flex-direction: column;align-items: center">
            <div class="desp-num">{{baoBiaoInfo?.sameTop}}</div>
            <div style="font-size: 14px;color: #666">同级排名</div>
          </div>
          <div style="flex: 0.8;justify-content: center" class="fixed-row">
            <div id="sourceEchart" style="height: 400px;width: 100%"></div>
          </div>
          <div style="display: flex;flex-direction: column;align-items: center">
            <div class="desp-num">{{baoBiaoInfo?.totalTop}}</div>
            <div style="font-size: 14px;color: #666">总体排名</div>
          </div>
        </div>
      </el-card>
      <el-card style="margin-bottom: 20px" >
        <div class="fixed-row">
          <div style="margin-right: 10px;font-size:14px">总得分对比</div>
          <!--          <el-select v-model="echartsMode1" placeholder="请选择图标渲染方式"-->
          <!--                     @change="changeEchartsMode1" style="width: 200px;margin-left: 15px">-->
          <!--            <el-option label="柱状图" value="柱状图"></el-option>-->
          <!--            <el-option label="折线图" value="折线图"></el-option>-->
          <!--          </el-select>-->
        </div>

        <div style="margin: 10px 0">
          <div class="fixed-row" style="justify-content: center">
            <div id="totalSourceEchart" style="height: 400px;width: 100%"></div>
          </div>
        </div>
      </el-card>
      <el-card style="margin-bottom: 20px">
        <div class="fixed-row">
          <div style="margin-right: 10px;font-size:14px">环节得分对比</div>
        </div>
        <div style="margin: 10px 0">
          <div class="fixed-row" style="justify-content: center">
            <div id="huanSourceEchart" style="height: 400px;width: 100%"></div>
          </div>
        </div>
      </el-card>
      <el-card style="margin-bottom: 20px">
        <div>
          <div style="margin-right: 10px;font-size:14px">错题展示</div>
          <!--      渲染问卷-->
          <WuJie name="wenjuanStatementviewError" url="http://129.211.212.235:3005/"></WuJie>
        </div>
      </el-card>
      <el-card style="margin-bottom: 20px">
        <div>
          <div style="margin-right: 10px;font-size:14px">细项得分</div>
          <div style="display: flex;align-items: center;margin-top: 10px">
            <el-select v-model="wenjuanMode" placeholder="请选择问卷渲染方式"
                       @change="changeToggleMode" style="width: 200px">
              <el-option label="正常模式" value="normal"></el-option>
              <el-option label="表格模式" value="table"></el-option>
            </el-select>
<!--            <el-select v-model="wenjuanModeTixing" placeholder="请选择问卷题型"-->
<!--                       @change="(val) => changeToggleMode1()" style="width: 200px;margin-left: 20px">-->
<!--              <el-option label="显示全部题型" value="showAll"></el-option>-->
<!--              <el-option label="显示错误题型" value="showError"></el-option>-->
<!--            </el-select>-->
          </div>
          <!--      渲染问卷-->
          <WuJie name="wenjuanStatementview" url="http://129.211.212.235:3005/"></WuJie>
        </div>
      </el-card>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
  import * as echarts from "echarts";
  import {screenStore} from '~/stores/modules/screen'
  import { onMounted, ref } from 'vue'
  import {useRoute,useRouter} from 'vue-router'
  import {getTableLocail,setTableLocail,toggleMode,getQuyu,getErrorCuOTi,exportErrorCuoTi,exportPDF1} from '~/api/public'
  import {getStateMentList,viewInfo,totalBaiInfo,exportDataInfo,startFanOrigin,getHuanXi} from '~/api/statementview'
  import domtoimage from 'dom-to-image';
  import {isClient} from '@vueuse/core'
  // import pkg from 'file-saver';
  // 动态导入jsPDF，避免SSR问题
  let yuanWenjuanJSON = ''
  let jsPDF = null
  let Document = null
  let Packer = null
  let Paragraph = null
  let ImageRun = null
  let SectionType = null
  let saveAs = null
  if (isClient) {
    import('file-saver').then(module => {
      saveAs = module.saveAs
    }).catch(err => {
      console.error('Failed to load saveAs:', err)
    })
    import('jspdf').then(module => {
      jsPDF = module.default
    }).catch(err => {
      console.error('Failed to load jsPDF:', err)
    })
    import('docx').then(module => {
      Document = module.Document
      Packer = module.Packer
      Paragraph = module.Paragraph
      ImageRun = module.ImageRun
      SectionType = module.SectionType
    }).catch(err => {
      console.error('Failed to load jsPDF:', err)
    })
  }
  let echart = echarts;
  let chart = null
  let chart1 = null
  let chart2 = null
  let periodId = ''
  let auditId = ''
  const screensStore = screenStore()
  const route = useRoute()
  const router = useRouter()
  const tablePropsArr = ref([
    {
      prop:'state',
      label:'审核状态',
      isHidden:true,
      width:'120px',
      slotRender:(row) => {
        return (
          `<el-tag
                type="primary"
                effect="dark"
            >
              ${row.taskName}
            </el-tag>`
        )
      }
    },
    {
      prop:'staffName',
      label:'访问员名称',
      isHidden:true
    },
    {
      prop:'outletsCode',
      label:'网点编号',
      isHidden:true,
      width: '200'
    },
    {
      prop:'outletsLevelName',
      label:'层级名称',
      isHidden:true,
      width: '200'
    },
    {
      prop:'outletsName',
      label:'网点简称',
      isHidden:true,
      width: '200'
    },
    {
      prop:'commitTime',
      label:'样本最终提交时间',
      isHidden:true,
      width: '180'
    },
    {
      prop:'questionnaireName',
      label:'问卷名称',
      isHidden:true
    },
    {
      prop:'score',
      label:'样本总得分',
      isHidden:true,
      width: '80'
    },
    {
      prop:'provinceName',
      label:'省份',
      isHidden:true,
      width: 180
    },
    {
      prop:'cityName',
      label: '城市',
      isHidden:true,
      width: 180
    },
    {
      prop:'areaName',
      label:'区县',
      isHidden:true,
      width: 180
    },
  ])
  const isEmpty = ref(false)
  const inputDrawer = ref(false)
  const tableData = ref([])
  // const echartsMode1 = ref('柱状图')
  // const echartsMode2 = ref('柱状图')
  const paging = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  })
  const searchData = reactive({
    state:'',
    outletsName:'',
    provinceName:'',
    cityName:'',
    areaName:'',
    addressList:[]
  })
  const sourceOption = reactive({
    tooltip: {
      formatter: '{a}: {c}'
    },
    series: [
      {
        name: '本期得分',
        type: 'gauge',
        detail: {
          formatter: '{value}',
          color:'red',
          padding:[10,0,0,0],
          fontSize:18,
        },
        data: [
          {
            value: 0,
            name: '本期得分',
          }
        ]
      }
    ]
  })
  const totalSourceOption = reactive({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    toolbox:{
      show:true,
      feature: {
        saveAsImage: {},  // 导出图片
        magicType: {show: true, type: ['line', 'bar']},
      }
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [],
        type: 'bar',
        barMaxWidth:20
      }
    ]
  })
  const huanSourceOption = reactive({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    toolbox:{
      show:true,
      feature: {
        saveAsImage: {},  // 导出图片
        magicType: {show: true, type: ['line', 'bar']},
      }
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [],
        type: 'bar',
        barMaxWidth:20
      }
    ]
  })
  const baoBiaoInfo = reactive({})
  const daQuyuList = ref([])
  const levelId1 = ref([])
  const wenjuanModeTixing = ref('showAll')
  onMounted(()=>{
    if (route.query.periodId) {
      isEmpty.value = true
      periodId = route.query.periodId
      getTableList()
    } else {
      isEmpty.value = false
    }
    getTableLocail('statementview').then(res => {
      if(res.code == 200){
        tablePropsArr.value = JSON.parse(res.data.fieldJson)
      }
      else{
        tablePropsArr.value = [
          {
            prop:'state',
            label:'审核状态',
            isHidden:true,
            width:'120px',
            fixed:"left"
          },
          {
            prop:'staffName',
            label:'访问员名称',
            isHidden:true,
            width: '150'
          },
          {
            prop:'outletsCode',
            label:'网点编号',
            isHidden:true,
            width: '200'
          },
          {
            prop:'outletsLevelName',
            label:'层级名称',
            isHidden:true,
            width: '200'
          },
          {
            prop:'outletsName',
            label:'网点简称',
            isHidden:true,
            width: '200'
          },
          {
            prop:'commitTime',
            label:'样本最终提交时间',
            isHidden:true,
            width: '180'
          },
          {
            prop:'questionnaireName',
            label:'问卷名称',
            isHidden:true,
            width: 200
          },
          {
            prop:'score',
            label:'样本总得分',
            isHidden:true,
            width: '150'
          },
          {
            prop:'provinceName',
            label:'省份',
            isHidden:true,
            width: 180
          },
          {
            prop:'cityName',
            label: '城市',
            isHidden:true,
            width: 180
          },
          {
            prop:'areaName',
            label:'区县',
            isHidden:true,
            width: 180
          },
        ]
      }
    })
    getQuyu({periodId:periodId,projectId:screensStore.selProjectId}).then(res => {
      if(res.code == 200){
        daQuyuList.value = res.data
      }
      else{
        daQuyuList.value = []
      }
    })

  })
  async function getMaxWidthHeight(arr) {
    const widthList = []
    const heightList = []
    let maxHeight = 0
    let maxWidth = 0
    for (let i = 0; i < arr.length; i++) {
      const url = arr[i]
      const { width, height } = await getImgWidthHeight(url)
      widthList.push(width)
      heightList.push(height)
    }
    // 把数组变成升序然后倒过来取第一个就是拿最大宽度
    maxWidth = widthList.sort().reverse()[0]
    maxHeight = heightList.sort().reverse()[0]
    return {
      maxWidth,
      maxHeight,
    }
  }
  //获取图片宽高
  function getImgWidthHeight(src) {
    return new Promise((resolve, reject) => {
      const img = new Image()
      // 处理跨域图片问题
      img.crossOrigin = 'anonymous'
      img.src = src
      // 图片是否有缓存 如果有缓存可以直接拿 如果没有缓存 需要从onload拿
      if (img.complete) {
        const { width, height } = img
        resolve({
          width,
          height,
        })
      } else {
        img.onload = function () {
          const { width, height } = img
          resolve({
            width,
            height,
          })
        }
      }
    })
  }
  const downloadDOCX = () => {
    window.document.querySelector("iframe[name=wenjuanStatementview]").contentWindow.getDownloadPDF().then(async resImg => {
      const imageUrl = await domtoimage.toPng(document.querySelector('.el-drawer__body'),{
        height:document.querySelector('.el-drawer__body').scrollHeight,
        width:document.querySelector('.el-drawer__body')?.scrollWidth,
        bgcolor: '#ffffff', // 可选：背景颜色
        quality: 1.0 // 可选：JPEG 图像质量（0-1）
      })
      const arrImg = [imageUrl,resImg]
      const { maxWidth, maxHeight } = await getMaxWidthHeight(arrImg)
      const arrData = []
      // 从top的位置开始加图片
      for (let i = 0; i < arrImg.length; i++) {
        const url = arrImg[i]
        const { width, height } = await getImgWidthHeight(url)
        arrData.push(new Paragraph({
          children: [
            new ImageRun({
              data: url,
              transformation: {
                width: width / 2.5,
                height: height / 2,
              },
            }),
          ],
        }))
      }
      const doc = new Document({
        sections: [
          {
            // type: SectionType.CONTINUOUS,
            // properties: {
            //   page: {
            //     size: {
            //       // 竖向A4: 210mm x 297mm
            //       width: maxWidth,
            //       height: maxHeight,
            //       unit: "twip" // 明确指定单位为twips
            //     },
            //     margin: {
            //       top: 20,
            //       right: 20,
            //       bottom: 20,
            //       left: 20,
            //       unit: "millimeter"
            //     },
            //     orientation: "portrait" // 竖向
            //   }
            // },
            children: [
              ...arrData
            ]
          }
        ]
      })

      // 生成并下载DOCX文件
      const blob = await Packer.toBlob(doc)
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '报表查看.docx'
      document.body.appendChild(a)
      a.click()

      // 清理
      setTimeout(() => {
        document.body.removeChild(a)
        URL.revokeObjectURL(url)
      }, 100)
    }).catch((e)=>{
    })
  }
  const downloadPDF = () => {
    window.document.querySelector("iframe[name=wenjuanStatementview]").contentWindow.getDownloadPDF().then(async resImg => {
      window.document.querySelector("iframe[name=wenjuanStatementviewError]").contentWindow.getDownloadPDF().then(async resErrImg => {
        const imageUrl = await domtoimage.toPng(document.querySelector('.el-drawer__body'),{
          height:document.querySelector('.el-drawer__body').scrollHeight + 730,
          width:document.querySelector('.el-drawer__body')?.scrollWidth,
          bgcolor: '#ffffff', // 可选：背景颜色
          quality: 1.0 // 可选：JPEG 图像质量（0-1）
        })
        const arrImg = [imageUrl,resErrImg,resImg]
        // 生成pdf
        // 第一个参数：l横向，p纵向
        // 第二个参数：计量单位: cm mm px等
        // 第三个参数：格式: 默认a4
        exportPDF1({base64Images:arrImg}).then(res => {
          ElMessage.success('报表信息导出成功')
          saveAs(res, '报表信息')
        })
      })

    }).catch((e)=>{
      ElMessage.error('问卷导出异常,请稍后再试！')
    })
  }
  function changeToggleMode1(json1 = ''){
    const json = JSON.stringify(json1 || yuanWenjuanJSON)
    let type = null
    type = 0
    getErrorCuOTi({json,type}).then(res => {
      if(res.code == 200){
        const arrRendJson = []
        const arrJson = JSON.parse(res.data)
        for(let val of arrJson){
          let obj = JSON.parse(val)
          obj.formGlobalConf.emptyText = '当前问题组暂无错题'
          arrRendJson.push(JSON.stringify(obj))
          continue
        }
        setTimeout(()=>{
          window.document.querySelector("iframe[name=wenjuanStatementviewError]").contentWindow.setWenJsonValue(arrRendJson,'yulan','yulan', screensStore.roles);
        },1000)
      }
      else{
        ElMessage.error(res.msg || '切换失败')
      }
    })
  }
  const wenjuanMode = ref('normal')
  function changeToggleMode(){
    const data = {
      json:JSON.stringify(wenjuanJson.value),
      type:wenjuanMode.value
    }
    toggleMode(data,'.jihua-submit').then(res => {
      if(res.code == 200){
        ElMessage.success('问卷模式切换成功')
        setTimeout(()=>{
          window.document.querySelector("iframe[name=wenjuanStatementview]").contentWindow.setWenJsonValue(JSON.parse(res.data),'yulan','yulan',screensStore.roles);
        },1000)
      }
    })
  }
  const getTablePropsList = (tablePropsArrs) => {
    tablePropsArr.value = tablePropsArrs
    const data = {
      name:'statementview',
      fieldJson:JSON.stringify(tablePropsArr.value)
    }
    setTableLocail(data)
  }
  function startFanshen(row){
    ElMessageBox.confirm(
      '是否确认启动反审！',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        startFanOrigin(row.id).then(res => {
          if(res.code == 200){
            ElMessage.success('反审启动成功')
            getTableList()
          }
          else{
            ElMessage.error(res.msg || '反审启动失败')
          }
        })
      })
  }
  // 去往期次选择页面
  function toIssueselect(){
    screensStore.activeHomeNav = '期次选择'
    router.replace({path:'/issueselect'})
  }
  const tableRowFormatter = (data) => {
    return `${data.cellValue}`
  }
  function onSearchList() {
    if(searchData.addressList.length){
      searchData.provinceName = searchData.addressList[0]
      searchData.cityName = searchData.addressList[1]
      searchData.areaName = searchData.addressList[2]
    }
    else{
      searchData.provinceName = ''
      searchData.cityName = ''
      searchData.areaName = ''
    }
    paging.currentPage = 1
    getTableList()
  }
  function onClearList() {
    levelId1.value = []
    Object.assign(searchData,{
      nodeName: '',
      outletsName: '',
      provinceName:'',
      cityName:'',
      areaName:'',
      addressList: []
    })
    paging.currentPage = 1
    getTableList()
  }

  function changeSize(val){
    paging.pageSize = val
    getTableList()
  }
  function changeCurrent(val){
    paging.currentPage = val
    getTableList()
  }
  function indexMethod(index:number){
    return (paging.currentPage - 1) * paging.pageSize + index + 1
  }

  const wenjuanJson = ref('')
  function openInputDrawer(type, row) {
    auditId = row.id
    wenjuanMode.value = 'normal'
    wenjuanModeTixing.value = 'showAll'
    inputDrawer.value = true
    nextTick(()=>{
      chart = echart.init(document.getElementById("sourceEchart"));
      chart1 = echart.init(document.getElementById('totalSourceEchart'))
      chart2 = echart.init(document.getElementById('huanSourceEchart'))
    })
    viewInfo(row.id).then(res => {
      if(res.code == 200){
        Object.assign(baoBiaoInfo,res.data)
        sourceOption.series[0].data[0].value = baoBiaoInfo.score || 0
        chart.setOption(sourceOption)
      }
      else{
        Object.assign(baoBiaoInfo,{
          ...{}
        })
        ElMessage({
          type:'error',
          message:res.msg || '报表信息获取失败！',
          appendTo:'.baobiao-submit'
        })
      }
    })
    totalBaiInfo(row.id).then(res => {
      if(res.code == 200){
        totalSourceOption.xAxis.data = []
        totalSourceOption.series[0].data = []
        const keys = Object.keys(res.data)
        const manInd = keys.findIndex(key => key == 'score')
        let arr = [keys[manInd]]
        keys.splice(manInd,1)
        let benkey = ''
        const benInd = keys.findIndex(key => key == 'current')
        benkey = keys[benInd]
        keys.splice(benInd,1)
        const newArr = keys.reverse()
        newArr.push(benkey)
        arr = arr.concat(...newArr)
        arr.forEach(key => {
          if(key == 'score'){
            totalSourceOption.xAxis.data.push('本期满分')
            totalSourceOption.series[0].data.push(res.data[key])
          }
          else if(key == 'current'){
            totalSourceOption.xAxis.data.push('本期得分')
            totalSourceOption.series[0].data.push(res.data[key])
          }
          else{
            totalSourceOption.xAxis.data.push(`上${key}期`)
            totalSourceOption.series[0].data.push(res.data[key])
          }
        })
      }
    })
    getHuanXi(row.id).then(res => {
      if(res.code == 200){
        if (!res.data.questJson) {
          wenjuanJson.value = ''
          yuanWenjuanJSON = ''
        } else {
          wenjuanJson.value = JSON.parse(res.data.questJson)
          yuanWenjuanJSON = JSON.parse(res.data.questJson)
        }
        if(res.data.groupSummed){
          // 环节得分对比
          const arr = JSON.parse(res.data.groupSummed)
          const arrTitle = arr.map(item => item.title)
          const arrscore = arr.map(item => item.groupScore)
          huanSourceOption.xAxis.data = arrTitle
          huanSourceOption.series[0].data = arrscore
        }
        changeToggleMode1()
        nextTick(()=>{
          if(window.document.querySelector("iframe[name=wenjuanStatementview]").contentWindow.setWenJsonValue){
            setTimeout(()=>{
              window.document.querySelector("iframe[name=wenjuanStatementview]").contentWindow.setWenJsonValue(wenjuanJson.value,'yulan','yulan',screensStore.roles);
            },1000)
          }
          else{
            setTimeout(()=>{
              window.document.querySelector("iframe[name=wenjuanStatementview]").contentWindow.setWenJsonValue(wenjuanJson.value,'yulan','yulan',screensStore.roles);
            },1000)
          }
          setTimeout(()=>{
            chart1.setOption(totalSourceOption)
            chart2.setOption(huanSourceOption)
          },1000)
        })
      }

    })

  }

  function getTableList() {
    const params = {
      ...searchData,
      periodId,
      current: paging.currentPage,
      size: paging.pageSize
    }
    delete params.addressList
    params.levelTreeList = []
    if(levelId1.value.length){
      levelId1.value.forEach(item => {
        params.levelTreeList.push(item)
      })
      params.levelTreeList = params.levelTreeList.join('&')
    }
    else{
      params.levelTreeList = null
    }
    getStateMentList(params).then(res => {
      if (res.code == 200) {
        tableData.value = res.data.records
        paging.total = res.data.total * 1
      } else {
        tableData.value = []
        paging.total = 0
      }
    })
  }

  function onExportData(){
    exportDataInfo(periodId).then(res => {
      ElMessage.success( '报表信息导出成功')
      saveAs(res,'报表信息')
    })
  }

  function exportErrorTi(){
    const params = {
      visitPlanId:auditId
    }
    exportErrorCuoTi(params).then(res => {
      ElMessage.success( '错题信息导出成功')
      saveAs(res,'错题信息')
    })
  }
</script>

<style scoped lang="less">
  .title-desp{
    font-size: 18px;
    color: #666;
    font-weight: 700;
  }

  .desp-num{
    font-size: 32px;
    color: #53a4f4;
    margin-bottom: 10px;
  }
</style>
